<template>
  <div>
    <nav-bar>
      <template v-slot:left>&lt;</template>
      <template v-slot:default>购物车</template>
    </nav-bar>
    <div class="cart-body">
      <van-checkbox-group
        v-model="result"
        @change="groupChange"
        ref="checkboxGroup"
      >
        <van-swipe-cell v-for="(item, index) in list" :key="index">
          <div class="good-item">
            <van-checkbox :name="item.id">
              <div class="good-img">
                <img :src="item.goods.cover_url" alt="" />
              </div>
              <div class="good-desc">
                <div class="good-title">
                  <span>{{ item.goods.title }}</span>
                  <span>x{{ item.goods.stock }}</span>
                </div>
                <div class="good-btn">
                  <div class="price">￥{{ item.goods.price + ".00" }}</div>
                  <van-stepper
                    integer
                    :min="1"
                    :max="item.goods.stock"
                    :model-value="item.num"
                    :name="item.id"
                    async-change
                    @change="onChange"
                  />
                </div>
              </div>
            </van-checkbox>
          </div>
          <template #right>
            <van-button
              square
              icon="delete"
              type="danger"
              class="delete-button"
              @click="deleteGood(item.id)"
            />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <van-submit-bar
      class="submit-all"
      :price="total * 100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-button class="check-btn" type="primary" @click="checkAll"
        >全选</van-button
      >
      <van-button class="check-btn" type="primary" @click="toggleAll"
        >反选</van-button
      >
    </van-submit-bar>
    <div class="empty" v-if="!list.length">
      <img
        src="https://th.bing.com/th/id/R43431104bd55623b929ddc40aa678c81?rik=jH2Aq4B7%2fy6WHg&riu=http%3a%2f%2fbgoo.amos.vip%2fimage%2fbj_baobei.png&ehk=hjsTX1%2f5cOOrD8GgSHMqD1urK1HSLH%2fjVCteppVGBMk%3d&risl=&pid=ImgRaw"
        alt=""
      />
      <span>购物车空空如也</span>
      <van-button
        class="empty-btn"
        round
        color="#1baeae"
        type="primary"
        block
        @click="goTo"
        >前往购物</van-button
      >
    </div>
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import {
  addCart,
  modifyCart,
  checkedCart,
  getCart,
  deleteCartItem,
} from "network/cart";
import { Toast } from "vant";
export default {
  name: "Shopcart",
  components: {
    NavBar,
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const checkboxGroup = ref(null);
    const status = reactive({
      list: [],
      result: [], // 购物车的id数组
      checkAll: true,
    });

    const goTo = () => {
      router.push({
        path: "home",
      });
    };

    // 异步改变购物车数量
    const onChange = (value, detail) => {
      // console.log(value)
      // console.log(detail.name);
      Toast.loading({ message: "修改中。。。", forbidClick: true });
      modifyCart(detail.name, { num: value }).then((res) => {
        // console.log(
        //   "已成功修改购物车" + detail.name + "，商品的数量为" + value
        // );
        // 同时改变本地list中的商品数量
        status.list.forEach((item) => {
          if (item.id == detail.name) {
            item.num = value;
          }
        });

        Toast.clear();
      });
    };

    // 复选框改变处理事件
    const groupChange = (result) => {
      status.result = result;
      console.log(status.result);
      // 改变服务器中的商品选中状态
      checkedCart({ cart_ids: result });
    };

    const checkAll = () => {
      checkboxGroup.value.toggleAll(true);
    };

    const toggleAll = () => {
      checkboxGroup.value.toggleAll(false);
    };

    const deleteGood = (id) => {
      // console.log(id);
      deleteCartItem(id).then(() => {
        // console.log("成功删除商品" + id);
        init(); // 重新初始化
        store.dispatch("updataCart"); // 改变vuex中的状态数量
      });
    };

    // 初始化购物车数据
    const init = () => {
      Toast.loading({ message: "加载中。。。", forbidClick: true });
      // console.log("init");
      getCart("include=goods").then((res) => {
        // console.log(res);
        status.list = res.data;
        status.result = res.data
          .filter((item) => item.is_checked == 1)
          .map((item) => item.id);
        Toast.clear();
      });
    };

    onMounted(() => {
      init();
    });

    // 通过计算属性 计算总价
    const total = computed(() => {
      let sum = 0;

      status.list
        .filter((item) => status.result.includes(item.id))
        .forEach(
          (item) => (sum += parseInt(item.num) * parseFloat(item.goods.price))
        );

      return sum;
    });

    // 根据总价格创建订单
    const onSubmit = () => {
      console.log(status.result.length)
      if (status.result.length == 0) {
        Toast.fail("请选择商品进行结算");
        return;
      } else {
        router.push({ path: "/createorder" });
      }
    };

    return {
      checkboxGroup,
      ...toRefs(status),
      goTo,
      onChange,
      groupChange,
      checkAll,
      toggleAll,
      deleteGood,
      total,
      onSubmit,
    };
  },
};
</script>

<style scoped lang="scss">
.cart-body {
  margin-top: 45px;
  .good-item {
    position: relative;
    padding: 5px;
    .good-img {
      display: inline-block;
      img {
        height: 100px;
        width: 100px;
      }
    }

    .good-desc {
      display: inline-block;
      position: absolute;
      text-align: center;
      width: 50%;
      margin-left: 20px;
      .good-title {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
      }
      .good-btn {
        display: flex;
        justify-content: space-between;
        margin-top: 50px;
        .price {
          text-align: center;
          height: 30px;
          line-height: 30px;
          color: red;
        }
      }
    }
  }

  .delete-button {
    height: 100%;
  }
}

.submit-all {
  margin-bottom: 50px;

  .check-btn {
    width: 60px;
    height: 30px;
    margin: 5px;
  }
}
.empty {
  img {
    width: 80%;
    height: auto;
    margin-top: 50px;
  }
  span {
    margin-top: 20px;
    display: block;
    text-align: center;
  }
  .empty-btn {
    width: 100px;
    height: 40px;
    margin-top: 20px;
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
  }
}
</style>
